﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Spider
{
    public class Product
    {
        private string mTitle;
        private string mDescription;
        private string mURL;
        private string mImageURL;
        private string mPrice;
        private string[] mFields;

        private static List<Product> mProList;
        private static Product mProduct;
        //private string productFileName = @"Data\Product.csv";
        public delegate void  AddProductHandler(Product AddProduct);
        public event AddProductHandler AddProductEvent;
 
        public Product()
        {

        }

        public Product(string[] Fields)
        {
            mFields = Fields;
        }

        public Product(string Title,string Description,string URL,string ImageURL,string Price)
        {
            mTitle = Title;
            mDescription = Description;
            mURL = URL;
            mImageURL = ImageURL;
            mPrice = Price;
        }

        public static Product Instance
        {
            get
            {
                if (mProduct == null)
                    mProduct = new Product();

                if (mProList == null)
                    mProList = new List<Product>();

                return mProduct;     
            }
        }

        public static void Reset()
        {
            mProduct = new Product();
            if (mProList != null)
                mProList.Clear();
        }

        public List<Product> ProductList
        {
            get
            {
                
                if (mProList == null)
                    mProList=new List<Product>();
                return mProList;
            }
        }

        public string[] Fields
        {
            get { return mFields; }
            set { mFields = value; }
        }

        public string Title
        {
            get { return mTitle; }
            set { mTitle = value; }
        }

        public string Description
        {
            get { return mDescription; }
            set { mDescription = value; }
        }

        public string URL
        {
            get { return mURL; }
            set { mURL = value; }
        }

        public string ImageURL
        {
            get { return mImageURL; }
            set { mImageURL = value; }
        }

        public string Price
        {
            get { return mPrice; }
            set { mPrice = value; }
        }

        public void AddProduct(Product Pro)
        {
            if (mProList == null)
                mProList = new List<Product>();


            if (!IsExistsPro(Pro.ImageURL, Pro.URL))
            {
                mProList.Add(Pro);
            }
            else
            {
                ModifyProduct(Pro);
            }
            if (AddProductEvent != null)
            {
                AddProductEvent(Pro);
            }
        }

        public void AddProduction(string Title, string Description, string URL, string ImageURL, string Price)
        {
            if (mProList == null)
                mProList = new List<Product>();
            Product pro = new Product(Title, Description, URL, ImageURL, Price);
            if (!IsExistsPro(ImageURL, URL))
            {
                mProList.Add(pro);
            }
            else
            {
                ModifyProduct(new Product(Title, Description, URL, ImageURL, Price));
            }
            if (AddProductEvent != null)
            {
                AddProductEvent(pro);
            }
        }

        /*写一个修改Product的函数*/
        public void ModifyProduct(Product pro)
        {
            Product p=null;
            foreach (Product temp in mProList)
            {
                if (temp.ImageURL == pro.ImageURL && temp.URL == pro.URL)
                {
                    p = temp;
                    break;
                }
            }
            if (p != null)
                mProList.Remove(p);
            mProList.Add(pro);
        }

        public bool IsExistsPro(string imageUrl, string URL)
        {
            bool blExistsTag = false;

            for (int i = 0; i < mProList.Count; i++)
            {
                if (mProList[i].ImageURL == imageUrl && mProList[i].URL == URL)
                {
                    blExistsTag = true;
                    break;
                }
            }
            return blExistsTag;
        }

        public void SaveProductList()
        {
            string filename = GetCurrentProductCSVFileName();

            if (string.IsNullOrEmpty(filename))
                return;

            StringBuilder builder = new StringBuilder();

            foreach (Product pro in mProList)
                builder.AppendFormat(ParseString(pro.Title) + "," + ParseString(pro.Description) + "," + ParseString(pro.URL) + "," + ParseString(pro.ImageURL) + "," + pro.Price + "\r\n");

            System.IO.StreamWriter write = null;

            try
            {
                write = System.IO.File.CreateText(filename);

                write.WriteLine(builder.ToString());
            }
            catch (System.Exception e)
            {
                Log.Instance.WriteException(e);
            }
            finally
            {
                write.Flush();
                write.Close();
            }
        }

        public void Clear()
        {
            mProList.Clear();
        }

        private string GetProductCSVFileName()
        {
            string filename = string.Empty;
            if(DataHandler.Instance.CurrentRule.Status.Equals(Convert.ToInt16(Status.STATUS_QUEUEDING)))
            {
                filename = DataHandler.Instance.CurrentRule.UrlPrefix;
                int index = filename.IndexOf('.');
                filename = filename.Substring(index + 1);
                filename=@"Data\"+filename+".csv";
            }
            return filename;
        }

        private string GetCurrentProductCSVFileName()
        {
            string filename = string.Empty;
            
            filename = DataHandler.Instance.CurrentRule.UrlPrefix;
            int index = filename.IndexOf('.');
            filename = filename.Substring(index + 1);
            filename = @"Data\" + filename + ".csv";

            return filename;
        }


        public void LoadProductList()
        {
            string filename = GetProductCSVFileName();
            if (string.IsNullOrEmpty(filename))
                return;

            System.IO.StreamReader reader = null;
            if (System.IO.File.Exists(filename))
                reader = System.IO.File.OpenText(filename);
            else
                return;

            Product pro = null;

            while (reader.Peek() != -1)
            {
                string strline = reader.ReadLine();
                if (string.IsNullOrEmpty(strline))
                    continue;
                string[] array = strline.Split(new string[] { "\"," }, StringSplitOptions.None);
                pro = new Product();

                pro.Title = UnParseString(array[0]);
                pro.Description = UnParseString(array[1]);
                pro.URL = UnParseString(array[2]);
                pro.ImageURL = UnParseString(array[3]);
                pro.Price = UnParseString(array[4]);

                mProList.Add(pro);
            }


            if (reader != null)
                reader.Close();
        }


        #region string process
        private string ParseString(string cell)
        {
            cell = cell.Replace("\"", "\"\"");

            return "\"" + cell + "\"";
        }

        private string UnParseString(string cell)
        {
            cell = cell.Replace("\"", string.Empty);

            return cell;
        }
        #endregion
    }
}
